package org.zjsru.user.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.zjsru.user.mapper.UserMapper;
import org.zjsru.user.pojo.User;
import org.zjsru.user.service.UserService;
import org.zjsru.user.util.JwtUtil;

import java.time.LocalDateTime;

/**
 * 用户服务实现类
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public User queryById(Long id) {
        return userMapper.findById(id);
    }

    @Override
    @Transactional
    public User register(User user) {
        // 检查用户名是否已存在
        User existingUser = userMapper.findByUsername(user.getUsername());
        if (existingUser != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setStatus(1); // 默认启用状态
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());

        // 保存用户
        userMapper.insert(user);
        log.info("用户注册成功，用户名: {}", user.getUsername());
        
        // 返回用户信息（不包含密码）
        user.setPassword(null);
        return user;
    }

    @Override
    public String login(String username, String password) {
        // 根据用户名查询用户
        User user = userMapper.findByUsername(username);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 检查用户状态
        if (user.getStatus() != 1) {
            throw new RuntimeException("用户已被禁用");
        }

        // 验证密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        // 生成JWT令牌
        String token = jwtUtil.generateToken(user.getUsername(), user.getId());
        log.info("用户登录成功，用户名: {}", username);
        
        return token;
    }

    @Override
    public User findByUsername(String username) {
        User user = userMapper.findByUsername(username);
        if (user != null) {
            user.setPassword(null); // 不返回密码
        }
        return user;
    }

    @Override
    @Transactional
    public User updateUser(User user) {
        user.setUpdateTime(LocalDateTime.now());
        int result = userMapper.update(user);
        if (result > 0) {
            log.info("更新用户信息成功，用户ID: {}", user.getId());
            return queryById(user.getId());
        }
        return null;
    }

    @Override
    public boolean checkUserStatus(Long userId) {
        User user = queryById(userId);
        return user != null && user.getStatus() == 1;
    }
} 